﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;


namespace Deployment.Data.SQL.Helpers
{
    internal static class SQLServerHelpers
    {

        internal static List<string> FindSQLServers()
        {
            List<String> serverList = new List<string>();
            DataTable instances = SqlDataSourceEnumerator.Instance.GetDataSources();
            foreach (DataRow row in instances.Rows)
            {
                string name = row["ServerName"].ToString();
                if (row["InstanceName"] != null && row["InstanceName"].ToString() != string.Empty)
                    name += string.Format(@"\{0}", row["InstanceName"]);
                serverList.Add(name);
            }
            serverList.Sort(StringComparer.CurrentCultureIgnoreCase);
            return serverList;
        }

        internal static List<string> GetAllDatabases(string serverName, bool? IntegratedSecurity, string userId, string password)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = serverName;
            if (IntegratedSecurity != null && IntegratedSecurity == true)
                builder.IntegratedSecurity = true;
            else
                builder.IntegratedSecurity = false;

            if (!string.IsNullOrEmpty(userId))
                builder.UserID = userId;
            if (!string.IsNullOrEmpty(password))
                builder.Password = password;
            List<string> databases = new List<string>();

            using (SqlConnection sqlConnection = new SqlConnection(builder.ConnectionString))
            {
                try
                {
                    sqlConnection.Open();
                    DataTable databaseList = sqlConnection.GetSchema("Databases");
                    sqlConnection.Close();


                    foreach (DataRow row in databaseList.Rows)
                        databases.Add(row["database_name"].ToString());
                }
                catch (Exception e) { }
            }
            return databases;
        }

        
    }
}
